package nju.se.alibaba;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import nju.se.alibaba.algorithm.Algorithm;
import nju.se.alibaba.algorithm.Algorithm_hds_month;
import nju.se.alibaba.algorithm.Algorithm_hds_pre;
import nju.se.alibaba.algorithm.PeriodAlgorithm;
import nju.se.alibaba.algorithm.UserBehaviourAlgorithm;
import nju.se.alibaba.dao.AlibabaDAO;

 class Alibaba {


	public static void main(String[] args) {
	
//		PeriodAlgorithm ma = new PeriodAlgorithm();
//		ma.writeToFile(ma.getResults(),"period_result.txt");
//		AlibabaDAO aDao = new AlibabaDAO();
//		UserBehaviourAlgorithm uba = new UserBehaviourAlgorithm();
//		;
//		uba.writeToFile(uba.getResults(), "behaviour_result.txt");
//		aDao.closeSqlSession();
//		Algorithm_hds_month alg = new Algorithm_hds_month();
//		alg.run();
//		Algorithm_hds_pre pre = new Algorithm_hds_pre();
//		pre.run();
		HashMap<Integer, HashSet<Integer>> periodResult = readFile("period_result.txt");
		HashMap<Integer, HashSet<Integer>> spmfResult = readFile("spmf_pre_result.txt");
		HashMap<Integer, HashSet<Integer>> behaviourResult = readFile("behaviour_result.txt");
		
		if (behaviourResult!=null&&periodResult!=null&&spmfResult!=null) {
			Set<Integer> keys = periodResult.keySet();
			for(Integer key:keys){
				if (behaviourResult.containsKey(key)) {
					HashSet<Integer> brSet = behaviourResult.get(key);
					HashSet<Integer> prSet = periodResult.get(key);
					brSet.addAll(prSet);
					behaviourResult.put(key, brSet);
				}
			}
			keys = spmfResult.keySet();
			for(Integer key:keys){
				if (behaviourResult.containsKey(key)) {
					HashSet<Integer> brSet = behaviourResult.get(key);
					HashSet<Integer> prSet = spmfResult.get(key);
					brSet.addAll(prSet);
					behaviourResult.put(key, brSet);
				}
			}
			
			Algorithm algorithm = new Algorithm();
			algorithm.writeToFile(behaviourResult, "finnal_result.txt");
		}
		
		
		
	}
	
	public static HashMap<Integer, HashSet<Integer>> readFile(String filename){
		HashMap<Integer, HashSet<Integer>>  result = new HashMap<Integer, HashSet<Integer>>();
		BufferedReader reader = null;
		try {
			FileReader outFile = new FileReader(new File(filename));
			reader = new BufferedReader(outFile);
			String tmp=null;
			while(null!=(tmp = reader.readLine())){
				String[] tmps = tmp.split("\t");
				int user_id = Integer.parseInt(tmps[0]);
				String[] brand = tmps[1].split(",");
				HashSet<Integer> brandSet=new HashSet<Integer>();;
				for (int i = 0; i < brand.length; i++) {
					brandSet.add(Integer.parseInt(brand[i]));
				}
				result.put(user_id, brandSet);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return result;
		
	}
	
}
